

package io. hei.commons.dynamic.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import io. hei.commons.dynamic.datasource.properties.DataSourceProperties;
import io. hei.commons.dynamic.datasource.properties.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置多数据源
 * @since 1.0.0
 */

/**
 * 通过@EnableConfigurationProperties(DynamicDataSourceProperties.class)
 * 将DynamicDataSourceProperties.class注入到Spring容器中
 */
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig {
    // 这里properties已经包含了yml配置中所对应的多数据源的属性了
    @Autowired
    private DynamicDataSourceProperties properties;

    /**
     * 通过@ConfigurationProperties与@Bean，将yml配置文件关于druid中的属性配置，转化成bean，并将bean注入到容器中
     * 这里作用是通过autowire作为参数应用到下面的dynamicDataSource()方法中
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 通过@Bean告知Spring容器，该方法会返回DynamicDataSource对象
     * 通过dynamicDataSource()配置多数据源选择逻辑，主要配置目标数据源和默认数据源
     */
    @Bean
    public DynamicDataSource dynamicDataSource(DataSourceProperties dataSourceProperties) {
        // 实例化自己实现的多数据源，其中实现了获取当前线程数据源名称的方法
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 设置多数据源属性
        dynamicDataSource.setTargetDataSources(getDynamicDataSource());

        // 工厂方法创建Druid数据源
        DruidDataSource defaultDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
        // 设置默认数据源属性
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);

        return dynamicDataSource;
    }

    private Map<Object, Object> getDynamicDataSource(){
        Map<String, DataSourceProperties> dataSourcePropertiesMap = properties.getDatasource();
        Map<Object, Object> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
        dataSourcePropertiesMap.forEach((k, v) -> {
            DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(v);
            targetDataSources.put(k, druidDataSource);
        });

        return targetDataSources;
    }

}